package com.matt.service.impl;

import com.matt.domain.*;
import com.matt.domain.course.ChildrenCourse;
import com.matt.domain.course.ChildrenCourseItem;
import com.matt.domain.course.CoursePlan;
import com.matt.foundation.constant.ChildrenConstant;
import com.matt.foundation.constant.ChildrenCourseConstant;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.query.OperationLogQuery;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.utils.ModelUtil;
import com.matt.repository.*;
import com.matt.repository.course.ChildrenCourseItemRepository;
import com.matt.repository.course.ChildrenCourseRepository;
import com.matt.repository.course.CoursePlanRepository;

import com.matt.service.remoteCall.SsoCallService;
import com.matt.service.TeachOperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;

/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2017/9/27
 * *******************************
 */
@Service
@Slf4j
public class TeachOperationLogServiceImpl implements TeachOperationLogService {


    @Autowired
    private TeachOperationLogRepository teachOperationLogRepository;

    @Autowired
    private MemVerificationCache memVerificationCache;

    @Autowired
    private ChildrenRepository childrenRepository;


    @Autowired
    private ChildrenCourseItemRepository childrenCourseItemRepository;

    @Autowired
    private CoursePlanRepository coursePlanRepository;

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    private ChildrenCourseRepository childrenCourseRepository;


    @Autowired
    private SsoCallService ssoCallService;

    @Transactional
    @Override
    public TeachOperationLog save(String code, String operationName, String description, String staffId, String areaId) {

        StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);

        TeachOperationLog log = TeachOperationLog.of(code,staffId, areaId, staff.getRealName(), operationName, description);
        return teachOperationLogRepository.save(log);
    }

    @Override
    public Page<TeachOperationLog> getLogByCondition(OperationLogQuery operationLogQuery) {
        Specification<TeachOperationLog> specification = new Specification<TeachOperationLog>() {
            @Override
            public Predicate toPredicate(Root<TeachOperationLog> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();

                if (StringUtils.isNotBlank(operationLogQuery.getDate())){
                    Map<String, Date> currentDay = DateUtil.getCurrentDayBeginAndEnd(operationLogQuery.getDate());
                    predicates.add(criteriaBuilder.and(criteriaBuilder.between(root.get("created"), currentDay.get("beg"), currentDay.get("end"))));
                }else {
                    Map<String, Date> currentDay = DateUtil.getCurrentDayBeginAndEnd(DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd"));
                    predicates.add(criteriaBuilder.and(criteriaBuilder.between(root.get("created"), currentDay.get("beg"), currentDay.get("end"))));
                }

                if (StringUtils.isNotBlank(operationLogQuery.getStaffId()))
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("staffId"), operationLogQuery.getStaffId())));

                if (StringUtils.isNotBlank(operationLogQuery.getAreaId())){
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("areaId"), operationLogQuery.getAreaId())));
                }
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.desc(root.get("created")));
                return query.getRestriction();
            }
        };
        Pageable pageable = PageRequest.of(operationLogQuery.getPageNum(), operationLogQuery.getPageSize());
        Page<TeachOperationLog> page = teachOperationLogRepository.findAll(specification, pageable);
        return page;
    }

    @Override
    public Page<TeachOperationLog> getMyLogByCondition(OperationLogQuery operationLogQuery) {
        Specification<TeachOperationLog> specification = new Specification<TeachOperationLog>() {
            @Override
            public Predicate toPredicate(Root<TeachOperationLog> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();

                if (StringUtils.isNotBlank(operationLogQuery.getDate())){
                    Map<String, Date> currentDay = DateUtil.getCurrentDayBeginAndEnd(operationLogQuery.getDate());
                    predicates.add(criteriaBuilder.and(criteriaBuilder.between(root.get("created"), currentDay.get("beg"), currentDay.get("end"))));
                }

                if (StringUtils.isNotBlank(operationLogQuery.getStaffId()))
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("staffId"), operationLogQuery.getStaffId())));

                if (StringUtils.isNotBlank(operationLogQuery.getAreaId())){
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("areaId"), operationLogQuery.getAreaId())));
                }
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.desc(root.get("created")));
                return query.getRestriction();
            }
        };
        Pageable pageable = PageRequest.of(operationLogQuery.getPageNum(), operationLogQuery.getPageSize());
        Page<TeachOperationLog> page = teachOperationLogRepository.findAll(specification, pageable);
        return page;
    }

    @Override
    public TeachOperationLog gardenAdviseLog(String childrenId, String content, String ticket, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            Children children = childrenRepository.getOne(childrenId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "添加教学建议", String.format("为 %s 宝宝添加了教学建议: %s", children.getName(), content));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save gardenAdviseLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addBirthdayRecordLog(String ticket, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "添加生日会记录", String.format("添加了生日会记录"));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save gardenAdviseLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog dropOutLog(String staffId, String areaId, String childrenId, String code) {
        try {
            Children children = childrenRepository.getOne(childrenId);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code, staffId, areaId, staff.getRealName(),
                    "退学", String.format("为 %s 宝宝执行了退学操作", children.getName()));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save dropOutLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog graduateLog(String staffId, String areaId, String childrenId, String code) {
        try {
            Children children = childrenRepository.getOne(childrenId);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "毕业", String.format("为 %s 宝宝执行了毕业操作", children.getName()));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save graduateLog error! ******************");
            return null;
        }
    }

//    @Override
//    public TeachOperationLog addContractLog(String staffId, String areaId, String childrenId, String childrenName, String courseName, String courseTime, String value) {
//        try {
//            Children children = childrenRepository.getOne(childrenId);
//            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
//            if (courseName.equals("SAT早教") || courseName.equals("SAT试听"))
//                courseTime = courseTime + " 次";
//
//            TeachOperationLog log = TeachOperationLog.of(value,  staffId, areaId, staff.getRealName(),
//                    "添加合同", String.format("为 %s 宝宝添加了合同 : %s %s", children == null ? childrenName : children.getName(), courseName, courseTime));
//            teachOperationLogRepository.save(log);
//            return log;
//        }catch (Exception e){
//            log.error("************* save addContractLog error! ******************");
//            return null;
//        }
//    }

//    @Override
//    public TeachOperationLog contractFinishLog(String ticket, String contractId, String value) {
//        try {
//            Contract contract = contractRepository.getOne(contractId);
//            Children children = childrenRepository.getOne(contract.getChildrenId());
//            String staffId = memVerificationCache.getStaffId(ticket);
//            String areaId = memVerificationCache.getAreaId(ticket);
//            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
//            TeachOperationLog log = TeachOperationLog.of(value,  staffId, areaId, staff.getRealName(),
//                    "结束合同", String.format("为 %s 宝宝结束了合同 : %s %s",  children.getName(), contract.getName(), contract.getDuration()));
//            teachOperationLogRepository.save(log);
//            return log;
//        }catch (Exception e){
//            log.error("************* save contractFinishLog error! ******************");
//            return null;
//        }
//    }
//
//    @Override
//    public TeachOperationLog contractRemarkLog(String contractId, String remark, String ticket, String value) {
//        try {
//            Contract contract = contractRepository.getOne(contractId);
//            Children children = childrenRepository.getOne(contract.getChildrenId());
//            String staffId = memVerificationCache.getStaffId(ticket);
//            String areaId = memVerificationCache.getAreaId(ticket);
//            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
//            TeachOperationLog log = TeachOperationLog.of(value,  staffId, areaId, staff.getRealName(),
//                    "给合同添加备注", String.format("为 %s 宝宝的合同 %s %s添加了备注 : %s",  children.getName(), contract.getName(), contract.getDuration()));
//            teachOperationLogRepository.save(log);
//            return log;
//        }catch (Exception e){
//            log.error("************* save contractRemarkLog error! ******************");
//            return null;
//        }
//    }

    @Transactional
    @Override
    public TeachOperationLog addEvaluatingMLog(String staffId, String areaId, String childrenId, String code) {
        try {
            Children children = childrenRepository.getOne(childrenId);
            Integer month = DateUtil.betweenMonths(new Date(), children.getBirthday());
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "创建托班月评", String.format("为 %s 宝宝创建了托班月评  (%s 月龄)",  children.getName(), month));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addEvaluatingMLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog evaluatingMLog(String staffId, String areaId, String childrenId, String code) {
        try {
            Children children = childrenRepository.getOne(childrenId);
            Integer month = DateUtil.betweenMonths(new Date(), children.getBirthday());
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "评估托班月评", String.format("评估了 %s 宝宝的托班月评  (%s月龄)",  children.getName(), month));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save evaluatingMLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addEvaluatingCBLog(String staffId, String areaId, String childrenName, String birthday, String code) {
        try {
            Integer month = DateUtil.betweenMonths(new Date(), DateUtil.parseToDate(birthday));
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "创建SAT初评", String.format("为 %s 宝宝创建了SAT初评  (%s 月龄)",  childrenName, month));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addEvaluatingCBLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog evaluatingCBLog(String ticket, String evaluatingCBRecordId, String code) {
        return null;
//        try {
//            EvaluatingCBRecord cbRecord = evaluatingCBRecordRepository.getOne(evaluatingCBRecordId);
//            Integer month = DateUtil.betweenMonths(new Date(), cbRecord.getBirthday());
//            String staffId = memVerificationCache.getStaffId(ticket);
//            String areaId = memVerificationCache.getAreaId(ticket);
//            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
//            TeachOperationLog log = TeachOperationLog.of(value,  staffId, areaId, staff.getRealName(),
//                    "评估SAT初评", String.format("评估了 %s 宝宝的SAT初评  (%s 月龄)",  cbRecord.getChildrenName(), month));
//            teachOperationLogRepository.save(log);
//            return log;
//        }catch (Exception e){
//            log.error("************* save evaluatingCBLog error! ******************");
//            return null;
//        }
    }

    @Transactional
    @Override
    public TeachOperationLog bindEvaluatingCBLog(String ticket, String childrenId, String code) {
        try {
            Children children = childrenRepository.getOne(childrenId);
            Integer month = DateUtil.betweenMonths(new Date(), children.getBirthday());
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "绑定SAT初评", String.format("为 %s 宝宝绑定了SAT初评  (%s 月龄)",  children.getName(), month));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save bindEvaluatingCBLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addEvaluatingCELog(String staffId, String areaId, String childrenId, String childrenCourseItemId, String code) {
        try {
            Children children = childrenRepository.getOne(childrenId);
            ChildrenCourseItem childrenCourseItem = childrenCourseItemRepository.getOne(childrenCourseItemId);
            CoursePlan coursePlan = coursePlanRepository.getOne(childrenCourseItem.getCoursePlanId());
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "SAT课堂评测", String.format("为 %s 宝宝添加了SAT课堂评测 : %s",  children.getName(), coursePlan.getCourseName()));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save evaluatingCBLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addEvaluateEarlyMLog(String ticket, String childrenId, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            Children children = childrenRepository.getOne(childrenId);
            Integer month = DateUtil.betweenMonths(new Date(), children.getBirthday());
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);

            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "创建SAT月评", String.format("为 %s 添加了SAT月评 (%s月龄)",  children.getName(), month));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save evaluateEarlyMLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addEvaluateLog(String ticket, String childrenId, String code) {
        return null;
    }

    @Transactional
    @Override
    public TeachOperationLog evaluateEarlyMLog(String ticket, String evaluatingCBRecordId, String code) {
        return null;
//        try {
//            String staffId = memVerificationCache.getStaffId(ticket);
//            String areaId = memVerificationCache.getAreaId(ticket);
//            EvaluatingCBRecord cbRecord = evaluatingCBRecordRepository.getOne(evaluatingCBRecordId);
//            Children children = childrenRepository.getOne(cbRecord.getChildrenId());
//            Integer month = DateUtil.betweenMonths(new Date(), children.getBirthday());
//            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
//
//            TeachOperationLog log = TeachOperationLog.of(value,  staffId, areaId, staff.getRealName(),
//                    "评估SAT月评", String.format("评估了 %s 宝宝的SAT月评 (%s月龄)",  children.getName(), month));
//            teachOperationLogRepository.save(log);
//            return log;
//        }catch (Exception e){
//            log.error("************* save evaluateEarlyMLog error! ******************");
//            return null;
//        }
    }

    @Transactional
    @Override
    public TeachOperationLog addHealthInfo(String ticket, String childrenId, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            String areaId = memVerificationCache.getAreaId(ticket);
            Children children = childrenRepository.getOne(childrenId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "新增儿保评测", String.format("为 %s 添加了儿保评测 (%s月龄)",  children.getName(), DateUtil.betweenMonths(new Date(), children.getBirthday())));
            teachOperationLogRepository.save(log);
            return null;
        }catch (Exception e){
            log.error("************* save addHealthInfo error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog modifyHealthInfo(String ticket, String childrenId, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            String areaId = memVerificationCache.getAreaId(ticket);
            Children children = childrenRepository.getOne(childrenId);
            Integer month = DateUtil.betweenMonths(new Date(), children.getBirthday());
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "修改儿保评测", String.format("修改了 %s 的儿保评测 (%s月龄)",  children.getName(), month));
            teachOperationLogRepository.save(log);
            return null;
        }catch (Exception e){
            log.error("************* save evaluateEarlyMLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addClassesLog(String ticket, String classesName, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);

            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "创建班级", String.format("创建了班级 %s",  classesName));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addClassesLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog modifyClassesLog(String ticket, String classesName, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);

            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "修改班级", String.format("修改了班级  %s",  classesName));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save modifyClassesLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog classesPlanLog(String ticket, String classesId, String baseTime, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            Classes classes = classesRepository.getOne(classesId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "班级排课", String.format("调整 %s 的基础日期为 %s ",  classes.getName(), baseTime));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save classesPlanLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog classesPrepareLog(String ticket, String classesId, String date, String content, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            Classes classes = classesRepository.getOne(classesId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "班级备课", String.format("备课 %s %s ",  classes.getName(), date));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save classesPrepareLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog checkInLog(String ticket, String childrenId, Integer checkType, Integer healthyStatus, String specialRecord, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            Children children = childrenRepository.getOne(childrenId);
            if (checkType== ChildrenConstant.CheckStatus.JOIN.codeOf()){
                TeachOperationLog log = TeachOperationLog.of("0440",  staffId, areaId, staff.getRealName(),
                        "托班签到", String.format("为 %s 宝宝签到, 晨检结果 : %s",  children.getName(), ChildrenConstant.HealthyStatus.HEALTHY.get(healthyStatus).valueOf()));
                teachOperationLogRepository.save(log);
                return log;
            }else if (checkType== ChildrenConstant.CheckStatus.LEAVE.codeOf()){
                TeachOperationLog log = TeachOperationLog.of("0441",  staffId, areaId, staff.getRealName(),
                        "托班请假", String.format("为 %s 宝宝请假, 理由: %s",  children.getName(), specialRecord));
                teachOperationLogRepository.save(log);
                return log;
            }
            return null;
        }catch (Exception e){
            log.error("************* save checkInLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog mulitCheckInLog(String ticket, String[] childrenIds,String code) {
        try {
        	
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            for (String childrenId : childrenIds) {
            Children children = childrenRepository.getOne(childrenId);
           
                TeachOperationLog log = TeachOperationLog.of("0440",  staffId, areaId, staff.getRealName(),
                        "托班签到", String.format("为 %s 宝宝签到, 晨检结果 : %s",  children.getName(), ChildrenConstant.HealthyStatus.HEALTHY.get(0).valueOf()));
                teachOperationLogRepository.save(log);
                return log;
            }
            return null;
        }catch (Exception e){
            log.error("************* save checkInLog error! ******************");
            return null;
        }
    }

    
    @Transactional
    @Override
    public TeachOperationLog addObservationLog(String ticket, String childrenId, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            Children children = childrenRepository.getOne(childrenId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "提交观测记录", String.format("为 %s 宝宝提交了观测记录 ",  children.getName()));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addObservationLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addLiveRecordLog(String ticket, Integer type, String[] childrenIds, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);

            List<Children> childrenList = childrenRepository.findByIdIn(childrenIds);
            List<String> names = childrenList.stream().map(o->o.getName()+"宝宝").collect(Collectors.toList());
            if (type== 1){
                TeachOperationLog log = TeachOperationLog.of("0451",  staffId, areaId, staff.getRealName(),
                        "提交照片", String.format("为 %s 提交了照片", ModelUtil.objectMapper.writeValueAsString(names)));
                teachOperationLogRepository.save(log);
                return log;
            }else if (type == 2){
                TeachOperationLog log = TeachOperationLog.of("0452",  staffId, areaId, staff.getRealName(),
                        "提交视频", String.format("为 %s 提交了视频",  ModelUtil.objectMapper.writeValueAsString(names)));
                teachOperationLogRepository.save(log);
                return log;
            }
            return null;
        }catch (Exception e){
            log.error("************* save addLiveRecordLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addChildrenCourseLog(String ticket, String childrenId, String[] coursePlanIds, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            Children children = childrenRepository.getOne(childrenId);
            List<CoursePlan> childrenList = coursePlanRepository.findByIdIn(coursePlanIds);
            List<String> titles = childrenList.stream().map(o->o.getCourseName()).collect(Collectors.toList());
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "给宝宝排课", String.format("为 %s 宝宝安排了SAT课程: %s", children.getName(), ModelUtil.objectMapper.writeValueAsString(titles)));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addChildrenCourseLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog modifyChildrenCourseLog(String ticket, String childrenCourseId, String[] coursePlanIds, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            ChildrenCourse childrenCourse = childrenCourseRepository.getOne(childrenCourseId);
            Children children = childrenRepository.getOne(childrenCourse.getId());
            List<CoursePlan> childrenList = coursePlanRepository.findByIdIn(coursePlanIds);
            List<String> titles = childrenList.stream().map(o->o.getCourseName()).collect(Collectors.toList());
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "修改宝宝排课", String.format("修改了 %s 宝宝的SAT课程为 : %s", children.getName(), ModelUtil.objectMapper.writeValueAsString(titles)));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save modifyChildrenCourseLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog modifyCourseTimeLog(String ticket, String childrenId, String remark, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            Children children = childrenRepository.getOne(childrenId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "修改剩余课时", String.format("修改了 %s 宝宝的剩余课时, 理由 : %s", children.getName(), remark));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save modifyCourseTimeLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog earlyPrepareLog(String ticket, String coursePlanId, String content, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            CoursePlan coursePlan = coursePlanRepository.getOne(coursePlanId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "SAT备课", String.format("备课 %s %s", coursePlan.getCourseName(), DateUtil.millisToDateTime(coursePlan.getCourseDate().getTime(), "yyyy-MM-dd")));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save earlyPrepareLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog satCheckInLog(String ticket, String courseItemId, Integer status, String remark, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);

            ChildrenCourseItem courseItem = childrenCourseItemRepository.getOne(courseItemId);
            Children children = childrenRepository.getOne(courseItem.getChildrenId());
            CoursePlan coursePlan = coursePlanRepository.getOne(courseItem.getCoursePlanId());
            if (status == ChildrenCourseConstant.ItemStatus.USED.codeOf()){
                TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                        "SAT签到", String.format("为 %s 宝宝签到, %s , 备注:%s ", children.getName(), coursePlan.getCourseName(), remark));
                teachOperationLogRepository.save(log);
                return log;
            }else if (status == ChildrenCourseConstant.ItemStatus.LEAVE.codeOf()){
                TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                        "SAT请假", String.format("为 %s 宝宝请假, %s , 备注:%s ", children.getName(), coursePlan.getCourseName(), remark));
                teachOperationLogRepository.save(log);
                return log;
            }else if (status == ChildrenCourseConstant.ItemStatus.USED.codeOf()){
                TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                        "SAT旷课", String.format("标记 %s 宝宝旷课, %s , 备注:%s ", children.getName(), coursePlan.getCourseName(), remark));
                teachOperationLogRepository.save(log);
                return log;
            }
            return null;
        }catch (Exception e){
            log.error("************* save satCheckInLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog modifyLiveRoomLog(String ticket, String roomName, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "修改摄像头名称", String.format("修改了摄像头名称 %s", roomName));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save modifyLiveRoomLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addTeachingAreaLog(String ticket, String areaName, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "新增教学区域", String.format("创建了教学区域 %s", areaName));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addTeachingAreaLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog modifyTeachingAreaLog(String ticket, String areaName, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "修改教学区域", String.format("修改了教学区域 %s", areaName));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addTeachingAreaLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addStaffLog(String ticket, String realName, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "添加员工", String.format("添加了新员工 %s", realName));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addTeachingAreaLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog modifyStaffLog(String ticket, String id, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);

            StaffDTO employee = ssoCallService.getStaffDTO(null, id);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "修改员工基本信息", String.format("修改了 %s 的基本信息", employee.getRealName()));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addTeachingAreaLog error! ******************");
            return null;
        }
    }

//    @Override
//    public TeachOperationLog modifyStaffRoleLog(String ticket, String id, String roleCode, String value) {
//        try {
//            String staffId = memVerificationCache.getStaffId(ticket);
//            String areaId = memVerificationCache.getAreaId(ticket);
//            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);
//
//            StaffDTO employee = ssoCallService.getStaffDTOById(id);
//            Role role = roleRepository.findByRoleCode(roleCode);
//            TeachOperationLog log = TeachOperationLog.of(value,  staffId, areaId, staff.getRealName(),
//                    "修改员工系统权限", String.format("将 %s 的权限修改为 %s", employee.getRealName(), role.getRoleName()));
//            teachOperationLogRepository.save(log);
//            return log;
//        }catch (Exception e){
//            log.error("************* save addTeachingAreaLog error! ******************");
//            return null;
//        }
//    }

    @Transactional
    @Override
    public TeachOperationLog dimissionLog(String ticket, String id, String code) {
        try {
            String staffId = memVerificationCache.getStaffId(ticket);
            String areaId = memVerificationCache.getAreaId(ticket);
            StaffDTO staff = ssoCallService.getStaffDTO(null, staffId);

            StaffDTO employee = ssoCallService.getStaffDTO(null, id);
            TeachOperationLog log = TeachOperationLog.of(code,  staffId, areaId, staff.getRealName(),
                    "离职", String.format("将 %s 设置为离职状态", employee.getRealName()));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addTeachingAreaLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addSystemProcessCourseItemLog(String childrenId, String planTitle, String areaId) {
        try {
            Children children = childrenRepository.getOne(childrenId);
            TeachOperationLog log = TeachOperationLog.of("9901",  null,  areaId, "系统",
                    "SAT课程过期", String.format("将 %s 的SAT课程 : %s 逾期未处理, 自动标记为已上课, 请及时添加课堂评测", children.getName(), planTitle));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addTeachingAreaLog error! ******************");
            return null;
        }
    }

    @Transactional
    @Override
    public TeachOperationLog addTargetRecordLog(StaffDTO staff, String typeName) {
        try {
            TeachOperationLog log = TeachOperationLog.of("8801",  staff.getId(),  staff.getAreaId(), staff.getRealName(),
                    "添加巡检记录", String.format("添加了 %s 的巡检记录",  typeName));
            teachOperationLogRepository.save(log);
            return log;
        }catch (Exception e){
            log.error("************* save addTeachingAreaLog error! ******************");
            return null;
        }
    }
}
